package thread;

//阻塞队列
//以数组为例，制作循环的阻塞队列
public class MyBlockingQueue {
    private int[] elem;
    private int size;
    private int head;
    private int tail;
    private Object locker = new Object();

    //构造方法
    public MyBlockingQueue(int capacity) {
        elem = new int[capacity];
    }

    //入队列
    public void put(int x) throws InterruptedException {
        synchronized (locker) {
            //队列已满，阻塞等待
            while (size == elem.length) {
                locker.wait();
            }
            elem[tail] = x;
            tail++;
            if (tail == elem.length) {
                tail = 0;
            }
            size++;
            locker.notify();//通知 take 队列已经有元素了
        }
    }

    //出队列
    public int take() throws InterruptedException {
        synchronized (locker) {
            //队列为空，阻塞等待
            while (size == 0) {
                locker.wait();
            }
            int ret = elem[head];
            head++;
            if (head == elem.length) {
                head = 0;
            }
            size--;
            locker.notify(); //通知 put 队列此时不满了
            return ret;
        }
    }
}
